package com.demo2do.boyle.backend.web.controller.customer;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.boyle.backend.service.customer.CustomerService;
import com.demo2do.boyle.backend.service.customer.WalletService;
import com.demo2do.boyle.backend.service.system.VariableService;
import com.demo2do.boyle.common.entity.AuditStatus;
import com.demo2do.boyle.common.entity.customer.Customer;
import com.demo2do.boyle.common.entity.customer.Source;
import com.demo2do.boyle.common.entity.customer.social.SocialAccount;
import com.demo2do.boyle.common.entity.customer.wallet.WalletRecord;
import com.demo2do.boyle.common.entity.system.Variable;
import com.demo2do.core.entity.Result;
import com.demo2do.core.persistence.support.Filter;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Page;


/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("")
@MenuSetting("menu-customer")
public class CustomerAuditController {

    private static final Logger logger = LoggerFactory.getLogger(CustomerAuditController.class);

    /** mapping table: variable	id **/
	private static final Integer PROPERTY_TYPE = 1;
	
    @Autowired
    private CustomerService customerService;

    @Autowired
    private WalletService walletService;
    
    @Autowired
    private VariableService variableService;
    

	/**
     * 
     * @return
     */
    @RequestMapping("/customer-audits")
    @MenuSetting("submenu-customer-audit")
    public ModelAndView list(Page page) {
        ModelAndView modelAndView = new ModelAndView("customer/audit/customer-audit-list");
        
        Filter filter = new Filter().addEquals("disabled", false)
                                    .addEquals("auditStatus", AuditStatus.AUDITING);
        
        int count = customerService.count(Customer.class, filter);
        modelAndView.addObject("count", count);
        
        if(count > 0) {
        	List<Customer> customers = customerService.list(Customer.class, filter, page);
            modelAndView.addObject("customers", customers);
        }
        
        return modelAndView;
    }

    /**
     * do search
     * 
     * @return
     */
    @RequestMapping(value = "/customer-audits/search", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-customer-audit")
    public ModelAndView onSearch(Page page, HttpServletRequest request,
            					@RequestParam(value = "nickName", required = false) String nickName,
            					@RequestParam(value = "mobile", required = false) String mobile,
            					@RequestParam(value = "source", required = false) Source source,
            					@RequestParam(value = "auditStatus", required = false) AuditStatus auditStatus,
            					@RequestParam(value = "createTimeBegin", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date createTimeBegin,
            					@RequestParam(value = "createTimeEnd", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date createTimeEnd) {

        ModelAndView modelAndView = new ModelAndView("customer/audit/customer-audit-list");

        Filter filter = new Filter().addEquals("disabled", false)
                                    .addLike("profile.nickName", nickName)
                                    .addLike("mobile", mobile)
                                    .addEquals("source", source)
                                    .addEquals("auditStatus", auditStatus)
                                    .addDateBetween("createTime", createTimeBegin, createTimeEnd);

        int count = customerService.count(Customer.class, filter);
        modelAndView.addObject("count", count);
        
        if(count > 0) {
        	List<Customer> customers = customerService.list(Customer.class, filter, page);
        	modelAndView.addObject("customers", customers);
        }

        // handle query string
        String queryString = request.getQueryString();
        Map<String, String> queries = StringUtils.parseQueryString(queryString);
        if(queries.containsKey("page")) {
            queries.remove("page");
        }
        
        modelAndView.addObject("queryString", StringUtils.toQueryString(queries));

        return modelAndView;
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping("/customer-audits/{id}")
    @MenuSetting("submenu-customer-audit")
    public ModelAndView view(@PathVariable("id") Integer id, Page page) {
        ModelAndView modelAndView = new ModelAndView("customer/audit/customer-audit-view");

        Customer customer = customerService.load(Customer.class, id);
        
        List<WalletRecord> walletRecords = walletService.listRecords(customer.getWallet(), page);
        Variable variable = variableService.queryObjectForId(PROPERTY_TYPE);

        modelAndView.addObject("customer", customer);
        modelAndView.addObject("walletRecords", walletRecords);
        modelAndView.addObject("variable", variable);

        return modelAndView;
    }
    
    /**
     * 
     * @param id
     * @return
     */
    @RequestMapping("/customers/{id}/audit")
    @MenuSetting("submenu-customer-audit")
    public ModelAndView audit(@PathVariable("id") Integer id) {

        ModelAndView modelAndView = new ModelAndView("customer/audit/customer-audit");

        Customer customer = customerService.load(Customer.class, id);
        modelAndView.addObject("customer", customer);

        return modelAndView;
    }
    
    /**
     * 
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/customers/{id}/audit", method=RequestMethod.PATCH)
    public String onAudit(@PathVariable("id") Integer id) {

        Result result = new Result();
        try {
            
            Customer customer = customerService.load(Customer.class, id);

            // check social account audited
            for(SocialAccount socialAccount : customer.getSocialAccounts()) {
                if(socialAccount.getAuditStatus().equals(AuditStatus.AUDITING)) {
                    return JsonUtils.toJsonString(result.fail().message("还有社交账户未审核"));
                }
            }

            customerService.update(customer.audit());

            result.success().message("更改成功");

        } catch(Exception e) {
            result.fail().message("服务器异常");
            logger.info("onPass()", e);
        }

        return JsonUtils.toJsonString(result);
    }

    /**
     * 
     * @param id
     * @return
     */
    @RequestMapping("/customers/{id}/social-account/{socialAccountId}/audit")
    @MenuSetting("submenu-customer-audit")
    public ModelAndView auditSocialAccount(@PathVariable("id") Integer customerId, @PathVariable("socialAccountId") Integer socialAccountId) {

        ModelAndView modelAndView = new ModelAndView("customer/audit/social-account-audit");
        Customer customer = customerService.load(Customer.class, customerId);
        SocialAccount socialAccount = customerService.loadSocialAccount(socialAccountId);
        Variable variable = variableService.queryObjectForId(PROPERTY_TYPE);
        
        modelAndView.addObject("customer", customer);
        modelAndView.addObject("socialAccount", socialAccount);
        modelAndView.addObject("variable", variable);
        return modelAndView;
    }
    
    /**
     * 
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/customers/{id}/social-account/{socialAccountId}/audit", method=RequestMethod.PATCH)
    public String onAuditSocialAccount(@RequestParam("socialAccountId") Integer id, @RequestParam("fans") int fans, @RequestParam("sign") String sign) {
    	
    	SocialAccount socialAccount = customerService.loadSocialAccount(id);
    	Customer customer = customerService.load(Customer.class, socialAccount.getCustomer().getId());
    	Result result = null;
    	
    	String smsUrl = null;
    	String smsName = null;
        String smsPassword = null;
        String smsContent = null;
        String smsSign = null;
    	
    	try {
    		//get property from resource
    		ClassPathResource resource = new ClassPathResource("/config/application.properties");
			Properties props = PropertiesLoaderUtils.loadProperties(resource);
			smsUrl = props.getProperty("sms.website");
			smsName = props.getProperty("sms.name");
			smsPassword = props.getProperty("sms.password");
			smsContent = props.getProperty("sms.content");
			
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
    	
    	if ("pass".equals(sign)) {
    		result = customerService.editSocialAccount(socialAccount.auditPass(fans));
		} else {
			result = customerService.editSocialAccount(socialAccount.auditNoPass(smsUrl,smsName,smsPassword,customer.getMobile(),smsContent,smsSign));
		}
        
        return JsonUtils.toJsonString(result);
    }
 
}
